package com.ltw.dreamer.report.service.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ltw.dreamer.report.mapper.FinancialReportDefineMapper;
import com.ltw.dreamer.report.model.FinancialReportDefine;
import com.ltw.dreamer.report.model.FinancialReportDefineExample;
import com.ltw.dreamer.report.model.FinancialReportDefineExample.Criteria;
import com.ltw.dreamer.report.service.FinancialReportDefineService;

@Service
public class FinancialReportDefineServiceImpl implements FinancialReportDefineService {
	@Resource
	private FinancialReportDefineMapper mapper = null;
	
	private final Map<String, String> tableMap = new HashMap<String, String>();
	public FinancialReportDefineServiceImpl() {
		tableMap.put("资产负债表", "balance_sheet");
		tableMap.put("现金流量表", "cash_flow");
		tableMap.put("利润表", "profit_statement");
	}
	
	public int queryColumnIndex(String reportName, String indexName) {
		FinancialReportDefineExample example = new FinancialReportDefineExample();
		Criteria criteria = example.createCriteria();
		criteria.andReportNameEqualTo(reportName);
		criteria.andIndexNameEqualTo(indexName);
		List<FinancialReportDefine> result = mapper.selectByExample(example);
		if (result == null || result.size() == 0) {
			return insertReportDefine(reportName, indexName);
		}
		
		return result.get(0).getIndexIterator();
	}

	private int insertReportDefine(String reportName, String indexName) {
		FinancialReportDefineExample example = new FinancialReportDefineExample();
		example.setOrderByClause("index_iterator desc");
		Criteria criteria = example.createCriteria();
		criteria.andReportNameEqualTo(reportName);
		List<FinancialReportDefine> result = mapper.selectByExample(example);
		int index = 1;
		if (result != null && result.size() != 0)
			index = result.get(0).getIndexIterator() + 1;
		
		FinancialReportDefine financialReportDefine = new FinancialReportDefine();
		financialReportDefine.setCreatedDate(Calendar.getInstance().getTime());
		financialReportDefine.setUpdatedDate(Calendar.getInstance().getTime());
		financialReportDefine.setIndexIterator(index);
		financialReportDefine.setIndexName(indexName);
		financialReportDefine.setTableName(tableMap.get(reportName));
		financialReportDefine.setReportName(reportName);
		mapper.insert(financialReportDefine);
		
		return index;
	}
}
